package com.shengqi.xinnongren.work.ui.home.fragments.home2sub;


import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.shengqi.xinnongren.R;
import com.shengqi.xinnongren.common.base.BaseMvpFragment;
import com.shengqi.xinnongren.common.config.user.UserManager;
import com.shengqi.xinnongren.common.utils.ImageUtils;
import com.shengqi.xinnongren.common.utils.ToastHelper;
import com.shengqi.xinnongren.work.ui.Global;
import com.shengqi.xinnongren.work.ui.goods.activities.GoodsDetailsActivity;
import com.shengqi.xinnongren.work.ui.home.model.ClassBean;
import com.shengqi.xinnongren.work.ui.home.model.GoodsBean;
import com.shengqi.xinnongren.work.ui.home.presenter.GoodsListPresenter;
import com.shengqi.xinnongren.work.ui.home.view.GoodsListView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * A simple {@link Fragment} subclass.
 */
public class GoodsListFragment extends BaseMvpFragment<GoodsListView, GoodsListPresenter> implements GoodsListView, OnRefreshListener, OnLoadMoreListener {

    @BindView(R.id.rv_goods_list)
    RecyclerView mRecyclerView;
    @BindView(R.id.rv_filter)
    RecyclerView mRvFilter;
    @BindView(R.id.sr_refresh)
    SmartRefreshLayout mRefreshLayout;

    int collectOperatePosition = -1;
    int currentPage = 0;
    List<GoodsBean> mGoodsBeanList = new ArrayList<>();

    private SpecialSaleAdapter mSpecialSaleAdapter;
    private String mClassId = "";
    private ClassBean.FilterBean mFilterBean;
    private String mPrefixClassStr = "";
    private List<ClassBean.FilterBean> mFilterBeanList = new ArrayList<>();
    private FilterAdapter mFilterAdapter;
    private boolean isLoginState;


    public GoodsListFragment() {
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isLoginState = UserManager.getInstance().isLogin();
    }

    @Override
    protected int setLayoutResource() {
        return R.layout.fragment_goods_list;
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    protected void initView() {
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setOnLoadMoreListener(this);
        mSpecialSaleAdapter = new SpecialSaleAdapter();
        mRecyclerView.setAdapter(mSpecialSaleAdapter);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mFilterAdapter = new FilterAdapter(getContext());
        mRvFilter.setAdapter(mFilterAdapter);
        mRvFilter.setLayoutManager(new GridLayoutManager(getContext(), 4));
    }


    @Override
    protected void initData() {

    }

    @Override
    protected void lazyLoadData() {
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isLoginState != UserManager.getInstance().isLogin()) {
            isLoginState = UserManager.getInstance().isLogin();
            getData(false);
        }
    }

    public void setClassInfo(String prefixClassStr, List<ClassBean.FilterBean> filterBeanList) {
        mGoodsBeanList.clear();
        mSpecialSaleAdapter.notifyDataSetChanged();
        mPrefixClassStr = prefixClassStr;
        mFilterBeanList.clear();
        if (filterBeanList != null)
            mFilterBeanList.addAll(filterBeanList);
        mClassId = "";
        mFilterAdapter.resetChoose();
        getData(false);
    }


    @Override
    protected GoodsListPresenter createPresenter() {
        return new GoodsListPresenter();
    }

    private void getData(boolean isLoadMore) {
        if (isLoadMore)
            ++currentPage;
        else
            currentPage = 0;
        String queryStr = "";
        if (!TextUtils.isEmpty(mPrefixClassStr))
            queryStr = mPrefixClassStr;
        if (!TextUtils.isEmpty(mClassId))
            queryStr += "," + mClassId;
        getPresenter().getGoodsList(queryStr, currentPage);
    }

    @Override
    public void showLoadingView() {
        showLoadingDialog();
    }

    @Override
    public void hideLoadingView() {
        hideLoadingDialog();
        resetRefreshLayout();
    }

    @Override
    public void onNetworkError() {
        hideLoadingView();
        resetRefreshLayout();
    }

    private void resetRefreshLayout() {
        mRefreshLayout.finishRefresh();
        mRefreshLayout.finishLoadMore();
    }

    @Override
    public void onGetListSucceed(List<GoodsBean> goodsBeanList) {
        resetRefreshLayout();
        if (currentPage == 0) {
            mGoodsBeanList.clear();
        }
        mGoodsBeanList.addAll(goodsBeanList);
        mSpecialSaleAdapter.notifyDataSetChanged();
    }

    @Override
    public void showCollectionResult(int state) {
        if (collectOperatePosition < 0)
            return;
        GoodsBean goodsBean = mGoodsBeanList.get(collectOperatePosition);
        goodsBean.setIsCollect(state);
        mSpecialSaleAdapter.notifyItemChanged(collectOperatePosition);
        collectOperatePosition = -1;
    }

    @Override
    public void onRequestFailed(String message) {
        ToastHelper.getInstance(getContext()).showWarn(message);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        getData(false);
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        getData(true);
    }

    class SpecialSaleAdapter extends RecyclerView.Adapter<SpecialSaleAdapter.Holder> {
        @NonNull
        @Override
        public SpecialSaleAdapter.Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            Holder holder = new Holder(getLayoutInflater().inflate(R.layout.item_class_goods_list, parent, false));
            holder.itemView.setOnClickListener(v -> GoodsDetailsActivity.start(getActivity(), mGoodsBeanList.get(holder.getAdapterPosition()).getComId()));
            holder.ivAddCart.setOnClickListener(v -> Global.showSpecificationDialog(getActivity(), mGoodsBeanList.get(holder.getAdapterPosition()).getComId()));
            holder.ivCollect.setOnClickListener(v -> {
                if (Global.checkLogin(getActivity())) {
                    collectOperatePosition = holder.getAdapterPosition();
                    GoodsBean goodsBean = mGoodsBeanList.get(holder.getAdapterPosition());
                    getPresenter().collectionGoods(goodsBean.getComId());
                }
            });
            return holder;
        }

        @Override
        public void onBindViewHolder(@NonNull SpecialSaleAdapter.Holder holder, int position) {
            GoodsBean goods = mGoodsBeanList.get(position);
            ImageUtils.showImage(getContext(), goods.getMainPic(), holder.ivCover);
            holder.tvTitle.setText(goods.getComName());
            holder.tvDesc.setText(goods.getPhrase());
            holder.tvOriginMoney.setText(goods.getOriginPlace());
            holder.tvPrice.setText(String.format("￥%s", goods.getPrice()));
            holder.tvUnit.setText(String.format("/%s", goods.getUnitName()));
            //是否为新品
            if (goods.getIsNew() == 1) {
                holder.flIsNew.setVisibility(View.VISIBLE);
            } else {
                holder.flIsNew.setVisibility(View.GONE);
            }
            clearTagStyle(holder);
            showTagByLabel(goods.getLabel(), holder);
            holder.ivCollect.setImageResource(goods.getIsCollect() == 1 ? R.mipmap.ic_goods_collected : R.mipmap.ic_goods_collect);
        }

        /**
         * 根据label 显示标签
         */
        private void showTagByLabel(List<String> label, Holder holder) {
            //1 满赠 2满减 3特价 4推荐 5限购 6热卖
            for (String lb : label) {
                switch (lb) {
                    case "1":
                        holder.mTvManZeng.setVisibility(View.VISIBLE);
                        break;
                    case "2":
                        holder.mTvManJian.setVisibility(View.VISIBLE);
                        break;
                    case "3":
                        holder.mTvTeJia.setVisibility(View.VISIBLE);
                        break;
                    case "4":
                        holder.mTvTuiJian.setVisibility(View.VISIBLE);
                        break;
                    case "5":
                        holder.mTvXianGou.setVisibility(View.VISIBLE);
                        break;
                    case "6":
                        holder.mTvReMai.setVisibility(View.VISIBLE);
                        break;
                }
            }
        }

        /**
         * 清除显示的标签
         */
        private void clearTagStyle(Holder holder) {
            holder.mTvManZeng.setVisibility(View.GONE);
            holder.mTvManJian.setVisibility(View.GONE);
            holder.mTvTeJia.setVisibility(View.GONE);
            holder.mTvTuiJian.setVisibility(View.GONE);
            holder.mTvXianGou.setVisibility(View.GONE);
            holder.mTvReMai.setVisibility(View.GONE);
        }

        @Override
        public int getItemCount() {
            return mGoodsBeanList.size();
        }

        public class Holder extends RecyclerView.ViewHolder {
            @BindView(R.id.fl_is_new)
            FrameLayout flIsNew;
            @BindView(R.id.tv_title)
            TextView tvTitle;
            @BindView(R.id.tv_desc)
            TextView tvDesc;
            @BindView(R.id.tv_price)
            TextView tvPrice;
            @BindView(R.id.tv_origin_place)
            TextView tvOriginMoney;
            @BindView(R.id.tv_unit)
            TextView tvUnit;
            @BindView(R.id.iv_cover)
            ImageView ivCover;
            @BindView(R.id.iv_add_cart)
            ImageView ivAddCart;
            @BindView(R.id.iv_collect)
            ImageView ivCollect;

            //1 满赠 2满减 3特价 4推荐 5限购 6热卖
            @BindView(R.id.tv_man_zeng)
            TextView mTvManZeng;
            @BindView(R.id.tv_man_jian)
            TextView mTvManJian;
            @BindView(R.id.tv_te_jia)
            TextView mTvTeJia;
            @BindView(R.id.tv_tui_jian)
            TextView mTvTuiJian;
            @BindView(R.id.tv_xian_gou)
            TextView mTvXianGou;
            @BindView(R.id.tv_re_mai)
            TextView mTvReMai;

            public Holder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }
    }

    public class FilterAdapter extends RecyclerView.Adapter<FilterAdapter.Holder> {

        private Context mContext;
        private int mDefaultColor = Color.GRAY;
        private int mChoseColor;
        private int mCurChosePosition = -1;

        public FilterAdapter(Context context) {
            mContext = context;
            mChoseColor = ContextCompat.getColor(context, R.color.colorPrimary);
        }

        @NonNull
        @Override
        public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View layout = LayoutInflater.from(mContext).inflate(R.layout.item_single_choose3, parent, false);
            return new Holder(layout);
        }

        @Override
        public void onBindViewHolder(@NonNull final Holder holder, final int position) {
            if (mCurChosePosition == position) {
                holder.mTvTitle.setTextColor(mChoseColor);
                holder.mTvTitle.setBackgroundResource(R.drawable.bg_class_choose_item_selected);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    holder.mTvTitle.setElevation(3);
                }
            } else {
                holder.mTvTitle.setTextColor(mDefaultColor);
                holder.mTvTitle.setBackgroundResource(R.drawable.bg_class_choose_item);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    holder.mTvTitle.setElevation(0);
                }
            }
            holder.mTvTitle.setText(mFilterBeanList.get(position).getName());
            holder.itemView.setOnClickListener(v -> {
                mCurChosePosition = holder.getAdapterPosition();
                notifyDataSetChanged();
                mClassId = mFilterBeanList.get(mCurChosePosition).getID();
                mGoodsBeanList.clear();
                getData(false);
            });
        }

        public void resetChoose() {
            setCurChosePosition(-1);
        }

        public void setCurChosePosition(int position) {
            mCurChosePosition = position;
            notifyDataSetChanged();
        }

        @Override
        public int getItemCount() {
            return mFilterBeanList.size();
        }

        class Holder extends RecyclerView.ViewHolder {
            TextView mTvTitle;

            Holder(View itemView) {
                super(itemView);
                mTvTitle = itemView.findViewById(R.id.tv_title);
            }
        }
    }
}
